<?php
namespace app\manage\controller;
use app\BaseController;
use think\App;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Model;

class Common extends BaseController
{
    /**
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        list($module, $controller, $action) = [app('http')->getName(), $this->request->controller(), $this->request->action()];
        $this->reqest_url = $controller."/".$action;
        $this->nav_name = "";
        $noLoginActs = ['Login']; //无需验证的控制器
        if (!in_array($this->reqest_url, $noLoginActs)) {
            if(session('user.id') == null){
                $url = '/manage/Login/index';
                $msg = ['code' => -10000, 'message' => '抱歉，您还没有登录获取访问权限！', 'url' => url($url)];
                return $this->request->isAjax() ? json($msg) : $this->redirect($url);
            }
            if (!$this->authCheck()) {
//                $msg = ['code' => -10001, 'message' => '抱歉，您还没有登录获取访问权限！'];
//                return $this->request->isAjax() ? json($msg) :$this->error("抱歉，您还没有登录获取访问权限");
//                exit();
            }
        }
        $this->leftMenu();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    public function leftMenu()
    {
        //获取当前用户的权力菜单
        $leftMenuId= Db::name("auth_group_access")
            ->alias("a")
            ->field("b.rules")
            ->join("auth_group b","a.group_id = b.id")
            ->where("uid","=",session("user.id"))
            ->find();
        //获取左边菜单栏
        $menu = Db::name("auth_rule")
            ->where("id","in",$leftMenuId['rules'])
            ->where('type', 1)
            ->where('status',0)
            ->field('condition,title,name,id,pid')
            ->order("orderlist asc")
            ->select()->toArray();
        $menu = $this->arr2tree($menu);
        //print_r($menu);
        View::assign("menu",$menu);
    }

    /**
     * 数组层级缩进转换
     * @param array $array 源数组
     * @param int   $pid
     * @param int   $level
     * @return array
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    function arr2tree($array, $rootId = 0,$level=1) {
        $return = array();
        foreach($array as $k=>$leaf) {
            $leaf['name'] = (string)url($leaf['name']);
            if($leaf['pid'] == $rootId) {
                $leaf["level"] = $level;
                foreach($array as $key=>$subleaf) {
                    if($subleaf['pid'] == $leaf['id']) {
                        // unset($array[$k]);
                        if($level==2){
                            break;
                        }
                        if($subleaf['name'] == $this->reqest_url){
                            $leaf['current']=1;
                            $array[$key]['current']=1;
                            $this->nav_name =$leaf['title']."|".$subleaf['title'];
                        }
                        $leaf['children'] = $this->arr2tree($array, $leaf['id'],$level+1);
                    }
                }
                $return[] = $leaf;
            }
        }
        return $return;
    }

    /**
     * 检查权限
     * @return array 返回结果
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zyj<535985755@qq.com>
     * Date: 2019/11/1
     */
    public function authCheck()
    {
        $noLoginActs = ['Index/index']; //无需验证的控制器
        if (!in_array($this->reqest_url, $noLoginActs)) {
            $this->hrefId = Db::name('auth_rule')->where('name', $this->reqest_url)->value('id');
            //当前管理员权限
            $map['a.id'] = Session::get('user.id');
            $rules = Db::name('admin')->alias('a')
                ->join("auth_group_access aga", "a.id = aga.uid")
                ->join('auth_group ag', 'aga.group_id = ag.id', 'left')
                ->where($map)
                ->value('ag.rules');
            //用户权限规则id
            $adminRules = explode(',', $rules);
            //不需要验证权限的控制器
//            $noruls =  Db::name('auth_rule')->where('status',"=",0)->column('id');
//            $this->adminRules = array_merge($adminRules, $noruls);

            if ($this->hrefId) {
                // 不在权限里面，并且请求为post
                if (!in_array($this->hrefId, $adminRules)) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }


}